package workflow

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"

	"github.com/gin-gonic/gin"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/internal/module/common/enum/common"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/pkg/response"
)

type UsageType int

const (
	PreCheck        UsageType = 1
	PreVerification UsageType = 2
	Changed         UsageType = 3
	Collect         UsageType = 4
)

var UsageTypeMap = common.EnumMap{
	int(PreCheck):        "预检查",
	int(PreVerification): "预校验",
	int(Changed):         "变更",
	int(Collect):         "采集",
}

func (p UsageType) String() string {
	return UsageTypeMap.String(int(p))
}
func ParseUsageType(s string) UsageType {
	for k, v := range UsageTypeMap {
		if v == s {
			return UsageType(k)
		}
	}
	return 0
}

func (p UsageType) MarshalJSON() ([]byte, error) {
	return json.Marshal(UsageTypeMap[int(p)])
}

func (p *UsageType) UnmarshalJSON(data []byte) error {
	var s string
	if err := json.Unmarshal(data, &s); err != nil {
		return err
	}
	for k, v := range UsageTypeMap {
		if v == s {
			*p = UsageType(k)
			return nil
		}
	}
	return fmt.Errorf("invalid UsageType: '%s', allowed: %v", s, UsageTypeMap)
}

func (p UsageType) IsValid() bool {
	_, exists := UsageTypeMap[int(p)]
	return exists
}

func (p UsageType) Value() (driver.Value, error) {
	if !p.IsValid() {
		return nil, fmt.Errorf("invalid UsageType: %d, allowed: %v", int(p), UsageTypeMap)
	}
	return int64(p), nil
}

func (p *UsageType) Scan(value interface{}) error {
	if value == nil {
		*p = 0
		return nil
	}
	if v, ok := value.(int64); ok {
		status := UsageType(int(v))
		if !status.IsValid() {
			return fmt.Errorf("invalid UsageType: %d, allowed: %v", int(v), UsageTypeMap)
		}
		*p = status
		return nil
	}
	return nil
}

func getUsageType() []common.Item {
	return UsageTypeMap.ToItems()
}

func WorkflowUsageTypeListHandler(c *gin.Context) {
	status := getUsageType()
	response.Success(c, status, "success")
}
